<?php

namespace Frieza\Modules\Article\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\ali\model\Data\AdsObj;
use Doraemon\model\Member;
use Doraemon\model\NewTag\Tag as dbTag;
use Doraemon\service\AppContentSync;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Doraemon\ali\model\Article\TodayArticle;
use Doraemon\model\Article;
use Doraemon\tools\ImgUrl;
use \Doraemon\ali\cache\Article\TodayArticle as cTodayArticle;
use \Doraemon\ali\model\Article\Article as AliArticle;
class TodayArticleLightAppController extends Controller
{

    const PAGE_SIZE = 20;
    const TAG_ID = 4345;
    const MONTH_ARR = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'];
    const START_YEAR = 2020;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    public function index(Request $request, Content $content, $year = 0, $month = 0)
    {
        $tab = new Tab();
        $map = [];
        $groupYearTime = $year > 0 ? $year : date("Y", time());
        $groupMonthTime = $month > 0 ? $month : date("m", time());
        $startGroupTime = strtotime($groupYearTime . "-" . $groupMonthTime . "-01");
        $endGroupTime = strtotime($groupYearTime . "-" . $groupMonthTime . "-01 +1 month -1 day");
        $map['show_time[>=]'] = $startGroupTime;
        $map['show_time[<=]'] = $endGroupTime;
        $map['ORDER'] = ['show_time' => 'DESC'];
        $groupInfo = TodayArticle::getAllArticlesByMap($map);
        $list = [];
        if ($groupInfo && is_array($groupInfo)) {
            $articleIds = array_unique(array_column($groupInfo, 'article_id')) ?: [];
            $articleInfo = [];
            if ($articleIds && is_array($articleIds)) {
                $articleInfo = Article::getBatchArticleByIds($articleIds);
                $articleInfo = array_combine(array_column($articleInfo, 'aid'), $articleInfo);
            }
            foreach ($groupInfo as $info) {
                $showTime = strtotime(date("Y-m-d", $info['show_time']));
                $info['show_time'] = $showTime;
                if ($articleInfo[$info['article_id']] && is_array($articleInfo[$info['article_id']])) {
                    $info['origin_title'] = $articleInfo[$info['article_id']]['title'];
                    $info['uid'] = $articleInfo[$info['article_id']]['uid'];
                    $info['cover_pic_url'] = ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $info['cover_pic_id'], ImgUrl::IMAGE_SIZE_OP_ORI);
                    $list[$showTime] = $info;
                }
            }
        }
        $childTab = new Tab();
        foreach (self::MONTH_ARR as $month) {
            if ($month == $groupMonthTime) {
                $childTab->add($month, $this->getArticleList($startGroupTime, $endGroupTime, $list), true);
            } else {
                $childTab->addlink($month, url('admin/article/todayarticlelightapp/' . $groupYearTime . "/" . $month));
            }
        }

        $tab->addLink('全部', url('admin/article/todayarticlelightapp'));

        $thisYear = date('Y', time());
        $yearList = range(self::START_YEAR, $thisYear + 1, 1); //从2020年开始
        foreach ($yearList as $year) {
            if ($groupYearTime == $year) {
                $tab->add($year, $childTab, true);
            } else {
                $tab->addLink($year, url('admin/article/todayarticlelightapp/' . $year));
            }
        }

        $content->row($tab);
        return $content
            ->header('')
            ->description('');
    }

    private function getArticleList($startGroupTime, $endGroupTime, $groupInfo)
    {
        //每月天数
        $daySum = (($endGroupTime - $startGroupTime) / 86400) + 1;
        $start_date = date("Y-m-d", $startGroupTime);
        $monthDayList = [];
        $uids = array_unique(array_column($groupInfo, 'uid'));
        for ($i = 0; $i < $daySum; $i++) {
            $showTime = strtotime($start_date . "+" . $i . " day");
            if ($groupInfo[$showTime] && is_array($groupInfo[$showTime])) {
                $monthDayList[] = $groupInfo[$showTime];
            } else {
                $monthDayList[]['show_time'] = $showTime;
            }
        }
        $gridModel = new pGridDataModel($monthDayList, count($monthDayList));
        // 获取是否授权， 调用用户组方法

        $sync = AppContentSync::getContent($uids);
        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($sync) {
            $grid->disableCreateButton();
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableFilter();
            $grid->disablePagination();
            $grid->column('show_time', '展示时间')->display(function () {
                return date("Y-m-d", $this->show_time);
            });
            $grid->column('article_id', '文章id');
            $grid->column("origin_tile", '整屋信息')->display(function () {
                if ($this->origin_title) {
                    return "<p>原标题:" . $this->origin_title . "</p><p>作者uid:" . $this->uid . "</p>";
                } else {
                    return '';
                }

            });
            $grid->column('title', '推荐标题');
            $grid->column("sync", '是否授权')->display(function () use ($sync) {
                if (empty($this->article_id)) {
                    return '';
                }
                if ($sync[$this->uid] == 1) {
                    return "<p>是</p>";
                } else {
                    return "<p>否</p>";
                }

            });
            $grid->column('cover_pic_url', '封面')->image();

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableEdit();
                $actions->disableDelete();
                if ($actions->row->id > 0) {
                    $actions->append('<a href="/admin/article/todayarticlelightapp/edit/' . $actions->row->show_time . '/' . $actions->row->id . '" class="fa fa-edit">编辑</a>');
                } else {
                    $actions->append('<a href="/admin/article/todayarticlelightapp/edit/' . $actions->row->show_time . '/0' . '" class="fa fa-edit">添加</a>');

                }

            });
        });
        return $listGrid->render();
    }

    public function edit(Request $request, Content $content, $showTime = 0, $id = 0)
    {
        $request = $request->all();
        return $content
            ->row(self::editAction($request, $showTime, $id));
    }

    //修改列表
    public function editAction($request = [], $showTime, $id = 0)
    {
        if ($id == 0) {
            $data = [];
            $data['show_time'] = $showTime;
        } else {
            $data = TodayArticle::getById($id);
            $data['category'] = explode(',', $data['tag_category']);
        }
        $tags = dbTag::getAllByWhere(['tag_status' => dbTag::STATUS_NORMAL, 'parent_id' => self::TAG_ID, 'ORDER' => ['tag_sort' => 'ASC']], ['id', 'tag']);
        $tags = array_column($tags, 'tag', 'id');
        $form = new Form($data);
        if ($id > 0) {
            $form->hidden('id');
        }
        $form->hidden("show_time");
        $form->html('<h7>' . date("Y-m-d", $data['show_time']) . ' </h7>', '推荐时间');
        $form->text("article_id", '文章id')->required();
        $form->text("title", "推荐标题");
        $form->imgUpload('cover_pic_id', '推荐封面', false, ['imgType' => ImgUrl::APPTYPE_OP, 'imgSize' => ImgUrl::IMAGE_SIZE_OP_ORI]);
        $form->multipleSelect("category", '分类')->options($tags);
        $form->action('/admin/article/todayarticlelightapp/save');
        return $form->render();
    }


    //提交修改
    public function editSubmit(Request $request)
    {
        $request = $request->all();
        $id = $request['id'] ?: 0;
        $showTime = $request['show_time'];
        $articleId = $request['article_id'];
        $info = Article::getArticle($articleId);
        if (empty($info)) {
            $error = new MessageBag([
                'title' => '文章不存在'
            ]);
            return back()->with(compact('error'))->withInput();
        }
        // 判断整屋是否在同步ali的表中
        $exist = AdsObj::getItem($articleId);
        if (empty($exist)) {
            $error = new MessageBag([
                'title' => '不在同步的数据中'
            ]);
            return back()->with(compact('error'))->withInput();
        }
        // 判断用户是否已经授权
        $sync = AppContentSync::getContent($info['uid']);
        if ($sync[$info['uid']] != 1) {
            $error = new MessageBag([
                'title' => '用户未授权'
            ]);
            return back()->with(compact('error'))->withInput();
        }
        $data['show_time'] = $showTime;
        $data['title'] = $request['title'] ?: '';
        $data['cover_pic_id'] = $request['cover_pic_id'] ?: '';
        $data['article_id'] = $articleId;
        $data['tag_category'] = implode(',', $request['category']);
        $data['addtime'] = time();
        $data['admin_id'] = Admin::user()->id;
        if ($id) {
            $rs = TodayArticle::updateById($id, $data);
        } else {
            $rs = TodayArticle::addArticle($data);
        }
        cTodayArticle::delTodayArticleItem();
        $year = date("Y", $showTime);
        $month = date("m", $showTime);
        if ($rs) {
            $success = new MessageBag([
                'title' => '操作成功'
            ]);
            return redirect('/admin/article/todayarticlelightapp/' . $year . '/' . $month)->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '操作失败'
            ]);
            return redirect('/admin/article/todayarticlelightapp/' . $year . '/' . $month)->with(compact('error'));
        }
    }


    //筛选数据
    public function getAll(Request $request, Content $content)
    {
        $pageSize = $request->input("per_page", 20);
        $info = $this->getFilterArticle($request);
        $groupInfo = $info['list'] ?: [];
        $total = $info['total'] ?: 0;
        $list = [];
        if ($groupInfo && is_array($groupInfo)) {
            $articleIds = array_unique(array_column($groupInfo, 'article_id')) ?: [];
            if ($articleIds && is_array($articleIds)) {
                $articleInfo = Article::getBatchArticleByIds($articleIds);
                $articleInfo = array_combine(array_column($articleInfo, 'aid'), $articleInfo);
            }
            foreach ($groupInfo as $info) {
                if ($articleInfo[$info['article_id']] && is_array($articleInfo[$info['article_id']])) {
                    $info['origin_title'] = $articleInfo[$info['article_id']]['title'];
                    $info['uid'] = $articleInfo[$info['article_id']]['uid'];
                    $info['cover_pic_url'] = ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $info['cover_pic_id'], ImgUrl::IMAGE_SIZE_OP_ORI);
                    $info['publish_time'] = $articleInfo[$info['article_id']]['publish_time'];
                    $list[] = $info;
                }
            }
        }

        $gridModel = new pGridDataModel($list, $total, [
            'perPage' => $pageSize
        ]);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel, $request) {
                $sync = $request->input("sync", 0);
                if ($sync == 1 || $sync == 2) {
                    $grid->disablePagination();
                } else {
                    $grid->paginate($gridModel->getPerPage());
                }
                $grid->disableExport();
                $grid->filter(function (\Encore\Admin\Grid\Filter $filter) {
                    // 去掉默认的id过滤器
                    $filter->disableIdFilter();
                    $filter->column(1 / 2, function ($filter) {
                        $filter->dropDown('Find', [
                            'article_id' => '文章id',
                            'uid' => 'uid',
                            'nick' => '用户昵称'
                        ]);
                        $filter->equal('sync', '是否授权')->radio([
                            0 => '未选择',
                            1 => '授权',
                            2 => '未授权',
                        ]);
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->between('show_time', '展示时间')->date();
                    });
                    //条件展开
                    $filter->expand();
                });
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();

                $grid->column('article_id', '文章id');
                $grid->column("origin_tile", '整屋信息')->display(function () {
                    if ($this->origin_title) {
                        return "<p>原标题:" . $this->origin_title . "</p><p>作者uid:" . $this->uid . "</p>";
                    } else {
                        return '';
                    }
                });;
                $grid->column('title', '推荐标题');
                $grid->column('cover_pic_url', '封面')->image();
                $grid->column('show_time', '展示时间')->display(function () {
                    return date("Y-m-d", $this->show_time);
                });

                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableEdit();
                    $actions->disableDelete();
                    $url = 'https://m.haohaozhu.cn/bangyang/' . $actions->row->article_id . '.html?preview=1';
                    $actions->prepend('<p style="white-space:nowrap"><a class="fa fa-envelope" href="javascript:layer.open({
                                type: 2,
                                title: \'预览\',
                                maxmin: true,
                                area: [\'800px\', \'500px\'],
                                content: \'' . $url . '\'
                            });">预览  </a></p>');
                });
            });
        $tab = new Tab();
        $tab->add('全部', $gridList->render(), true);
        $thisYear = date('Y', time());
        $yearList = range(self::START_YEAR, $thisYear + 1, 1); //从2020年开始
        foreach ($yearList as $year) {
            $tab->addLink($year, url('admin/article/todayarticlelightapp/' . $year));
        }
        $content->row($tab);
        return $content
            ->header('')
            ->description('');
    }


    private function getFilterArticle(Request $request)
    {
        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);
        $requestParams = $request->all();
        if ($requestParams['sync'] == 1 || $requestParams['sync'] == 2) {
            $sql = 'select *,CONV(RIGHT(article_id , 7), 36, 10) as uid from today_article_pool';
            $groupInfo = TodayArticle::query($sql)->fetchAll();
            $uidColumn = array_column($groupInfo, 'uid');
            $sync = AppContentSync::getContent(array_unique($uidColumn));
            foreach ($groupInfo as $key => $item) {
                $ids = AliArticle::getArticleListWhere(['article_status' => AliArticle::STATUS_NORMAL], 'aid');
                if ($requestParams['sync'] == 2) {
                    // 未授权把已授权的过滤掉
                    if (isset($sync[$item['uid']]) && $sync[$item['uid']] == 1) {
                        unset($groupInfo[$key]);
                    }
                    if (in_array($item['article_id'], $ids)) {
                        unset($groupInfo[$key]);
                    }
                }
                if ($requestParams['sync'] == 1) {
                    // 已授权把位授权的过滤掉
                    // 取出授权Article表中的数据
                    if (!isset($sync[$item['uid']]) || $sync[$item['uid']] == 2) {
                        unset($groupInfo[$key]);
                    }
                    if (!in_array($item['article_id'], $ids)) {
                        unset($groupInfo[$key]);
                    }
                }
            }
            $total = count($groupInfo);
            return [
                'list' => $groupInfo,
                'total' => $total
            ];
        }
        if ($requestParams['uid'] || $requestParams['nick']) {
            if ($requestParams['nick']) {
                $uid = Member::getUidByNick($requestParams['nick']);
                if ($uid) {
                    $requestParams['uid'] = $uid;
                }
            }
            $uid = $requestParams['uid'];
            if ($uid) {
                if ($requestParams['show_time']['start'] && $requestParams['show_time']['end']) {
                    $sql = "select *,CONV(RIGHT(article_id , 7), 36, 10) as author from today_article_pool where show_time BETWEEN " . strtotime($requestParams['show_time']['start']) . " AND " . strtotime($requestParams['show_time']['end']) . " having author=" . $uid;
                } else {
                    $sql = 'select *,CONV(RIGHT(article_id , 7), 36, 10) as author from today_article_pool  having author=' . $uid;
                }
                $groupInfo = TodayArticle::query($sql)->fetchAll();
                $total = count($groupInfo);

            } else {
                $groupInfo = [];
                $total = 0;
            }
        } else {
            if ($requestParams['show_time']['start'] && $requestParams['show_time']['end']) {
                $map['show_time[<>]'] = [strtotime($requestParams['show_time']['start']), strtotime($requestParams['show_time']['end'])];
            }
            if ($requestParams['article_id']) {
                $map['article_id'] = $requestParams['article_id'];
            }
            $map['ORDER'] = ['show_time' => 'DESC'];
            $total = TodayArticle::count($map);

            $map['LIMIT'] = [($page - 1) * $pageSize, $pageSize];
            $groupInfo = TodayArticle::getAllArticlesByMap($map);
        }
        return [
            'list' => $groupInfo,
            'total' => $total
        ];
    }
}